import {
  login,
  logout,
  getInfo,
  platformToken
} from '@/api/login'

import { getToken, setToken, removeToken } from '@/shared/auth'

// @ts-ignore
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state: { token: any }, token: any) => {
      state.token = token
    },
    SET_NAME: (state: { name: any }, name: any) => {
      state.name = name
    },
    SET_AVATAR: (state: { avatar: any }, avatar: any) => {
      state.avatar = avatar
    },
    SET_ROLES: (state: { roles: any }, roles: any) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state: { permissions: any }, permissions: any) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }: any, userInfo: { username: string; password: any; code: any; uuid: any }) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise<void>((resolve, reject) => {
        login(username, password, code, uuid).then((res: any) => {
          const { token }: any = res;
          setToken(token)
          commit('SET_TOKEN', token)
          resolve()
        }).catch((error: any) => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }: any) {
      return new Promise((resolve, reject) => {
        getInfo().then((res: unknown) => {
          const { user, roles, permissions }: any = res;
          const avatar = user.avatar === '' ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_API + user.avatar
          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', roles)
            commit('SET_PERMISSIONS', permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch((error: any) => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }: any) {
      return new Promise<void>((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch((error: any) => {
          reject(error)
        })
      })
    },

    PlatformToken({ state }: any) {
      return new Promise((resolve, reject) => {
        platformToken(state.token).then((res: any) => {
          console.log(res)
        }).catch((error: any) => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }: any) {
      return new Promise<void>(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
